<?php

// +---------------------------------------------+
// |     Copyright  2010 - 2018 InterPhoto       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+


include('includes/InterPhoto.Core.php');

header("Expires: Mon, 18 Jul 1988 01:08:08 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0


$action = ForceIncomingString('action', 'registerform');
if (IsGet('sid') AND IsGet('key')){
	$action = 'registerverify';
}

if(!$mainsettings['siteAllowRegister']){
	$action = 'registerform';
}

$smarty = new InterPhoto;
$showform = 0;
$pagenav = '<a href="'.GetUrl('index.php').'">'.$langs['home'].'</a> '.$langs['nav'].' <a href="'.GetUrl('register.php').'">'.$langs['member'].$langs['register'].'</a>';


if($action == 'insertuser')
{
	$username        = ForceIncomingString('username');
	$password        = ForceIncomingString('password');
	$repassword = ForceIncomingString('repassword');
	$email           = ForceIncomingString('email');
	$vvckey           = ForceIncomingInt('vvckey');
	$vvc           = ForceIncomingString('vvc');
	$agreeterms           = ForceIncomingInt('agreeterms');

	if(strlen($username) == 0){
		$errors[] = $sys_langs['please_enter'].$langs['username'];
	}elseif(!IsName($username)){
		$errors[] = $sys_langs['badusername'];
	}elseif($registered = $DB->query_first("SELECT userid FROM " . TABLE_PREFIX . "users WHERE username = '$username'")){
		$errors[] = $sys_langs['usernamed'];
	}

	if(strlen($password) == 0){
		$errors[] = $sys_langs['please_enter'].$langs['password'];
	}elseif(!IsPass($password)){
		$errors[] = $sys_langs['badpassword'];
	}elseif($password != $repassword){
		$errors[] = $sys_langs['passnotsame'];
	}

	if(strlen($email) == 0){
		$errors[] = $sys_langs['please_enter'].$langs['email'];
	}elseif(!IsEmail($email)){
		$errors[] = $sys_langs['bademail'];
	}elseif($DB->query_first("SELECT email FROM " . TABLE_PREFIX . "users WHERE email = '$email' ")){
		$errors[] = $sys_langs['emailed'];
	}

	if(!CheckVVC($vvckey, $vvc)){
		$errors[] = $sys_langs['badvvc'];
	}

	if(!$agreeterms){
		$errors[] = $sys_langs['mustagree'];
	}

	if(!isset($errors))
	{

		if($mainsettings['siteRegisterCheck'] == 'Auto'){
			$DB->query("INSERT INTO " . TABLE_PREFIX . "users VALUES (NULL, 3, 1, '$username', '".md5($password)."', '', '$email', '".time()."', 0, '', '', '', '', '', '', '', '')");

			$userid = $DB->insert_id();
			CreateSession($userid);
			$userinfo = GetUserInfo($userid);
			$success = $sys_langs['registerfinished'].'<BR>'.$sys_langs['yourusername'].' '.$username.'<BR>'.$sys_langs['yourpassword'].' '.$password;

		}elseif($mainsettings['siteRegisterCheck'] == 'AdminVerify'){
			$DB->query("INSERT INTO " . TABLE_PREFIX . "users VALUES (NULL, 3, 0, '$username', '".md5($password)."', '', '$email', '".time()."', 0, '', '', '', '', '', '', '', '')");

			$success = $sys_langs['needadminverify'].'<BR>'.$sys_langs['yourusername'].' '.$username.'<BR>'.$sys_langs['yourpassword'].' '.$password;

		}elseif($mainsettings['siteRegisterCheck'] == 'EmailVerify'){
			$verifycode = PassGen(8);

			$DB->query("INSERT INTO " . TABLE_PREFIX . "users VALUES (NULL, 3, 0, '$username', '".md5($password)."', '$verifycode', '$email', '".time()."', 0, '', '', '', '', '', '', '', '')");

			$userid = $DB->insert_id();

			require_once (BASEPATH. 'library/phpmailer/class.phpmailer.php');

			$mail = new PHPMailer();

			if($mainsettings['siteUseSmtp'] != '1'){
				$mail->IsMail();
				$mail->Sender      =  $mainsettings['siteEmail'];
			}else{
				$mail->IsSMTP();
				$mail->Host =  $mainsettings['siteSmtpHost'];
				$mail->Port = $mainsettings['siteSmtpPort'];

				$mail->SMTPAuth = true;
				$mail->Username = $mainsettings['siteSmtpUser'];
				$mail->Password = $mainsettings['siteSmtpPassword'];
				$mail->Sender      =  $mainsettings['siteSmtpEmail'];
			}


			$mail->From      =  $mainsettings['siteEmail'];
			$mail->FromName      =  $mainsettings['siteCopyright'];
			$mail->AddReplyTo ($mainsettings['siteEmail'], $mainsettings['siteCopyright']);   
			
			$mail->Subject  = $sys_langs['registerverify'];

			$message        = "\r\n".$sys_langs['thanksforregister'].":\r\n\r\n";
			$message        .= $sys_langs['yourusername']." ".$username."\r\n";
			$message        .= $sys_langs['yourpassword']." ".$password."\r\n\r\n";
			$message        .= $sys_langs['clickforverify']."\r\n";

			$message       .= "<a href=\"" . BASEURL . "register.php?key=".base64_encode($userid)."&sid=" . md5($username .COOKIE_KEY.md5($password).$verifycode) . "\" target=\"_blank\">" .BASEURL . "register.php?key=".base64_encode($userid)."&sid=" . md5($username .COOKIE_KEY.md5($password).$verifycode) . "</a>\r\n";

			$message        .= "\r\n\r\n\r\n\r\n".$mainsettings['siteCopyright']."\r\n".DisplayDate(time())."\r\n";

			$mail->Body     = nl2br($message);
			$mail->AddAddress($email);

			if($mail->Send()){
				$success = $sys_langs['needemailverify'];
			}else{
				$errortitle = $langs['register'].$sys_langs['error'];
				$errors = $sys_langs['registerfailed'];
				$DB->query("DELETE FROM " . TABLE_PREFIX . "users WHERE userid = '$userid' ");
				$action = 'registerform';
			}

		}
		
		$successtitle = $sys_langs['thanksforregister'];

	}else{
		$errortitle = $langs['register'].$sys_langs['error'];
		$action = 'registerform';
	}
}


if($action == 'registerverify')
{
	$userid = ForceInt(base64_decode(ForceIncomingString('key')));
	$sid = ForceIncomingString('sid');
	if($userid AND isName($sid)){
		$user = $DB->query_first("SELECT activated, username, password, verifycode FROM " . TABLE_PREFIX . "users WHERE userid = '$userid'");

		if(isset($user))
		{
			if($sid == md5($user['username'] .COOKIE_KEY.$user['password'].$user['verifycode']))
			{
				if($user['activated'] == '0'){
					$DB->query("UPDATE " . TABLE_PREFIX . "users SET activated = '1', verifycode = ''  WHERE userid = '$userid' ");
				}
				CreateSession($userid);
				$userinfo = GetUserInfo($userid);
				$success = $sys_langs['registerfinished'];
				$successtitle = $sys_langs['thanksforregister'];
			}else{
				$verifyfailed = true;
			}
		}else{
			$verifyfailed = true;
		}

	}else{
		$verifyfailed = true;
	}

	if($verifyfailed){
		$errortitle = $sys_langs['emailverify'].$sys_langs['error'];
		$errors = $sys_langs['emailverify_err'];
		$action = 'registerform';
	}
}



if($action == 'registerform')
{
	if(isset($errors))
	{
		$user = array('username'     => $username,
			  'password'     => $password,
			  'repassword'     => $repassword,
			  'email'     => $email);

	}else{
		$user = array();
	}

	if($userinfo['userid']){
		header("Location: ".GetUrl('mydesk.php'));
		exit();
	}elseif(!$mainsettings['siteAllowRegister']){
		$showform = 0;
		$errortitle = $langs['register'].$sys_langs['error'];
		$errors = $sys_langs['registeroff'];
	}else{
		$showform = 1;
		$smarty->assign('user', $user);
		$smarty->assign('vvckey', CreateVVC());
	}

}

if(!$mainsettings['siteAllowGuest']){
	$smarty->assign('loginforview', $sys_langs['loginforview']);
}else{
	$getimages = $DB->query("SELECT i.imageid, i.path, i.filename, i.title FROM " . TABLE_PREFIX . "images i LEFT JOIN  " . TABLE_PREFIX . "categories c ON (c.categoryid = i.categoryid) WHERE (i.usergroupids = 'all' OR i.usergroupids LIKE '%(".$userinfo['groupid'].")%') AND i.actived = 1 AND c.actived = 1 ORDER BY rand() LIMIT 10");

	$images = $DB->getrows($getimages);

	$smarty->assign('images', $images);
}


$smarty->assign('showform', $showform);
$smarty->assign('pagenav', $pagenav);
$smarty->assign('userinfo', $userinfo);
$smarty->assign('pagetitle', $langs['member'].$langs['register'] . ' - ' .$mainsettings['siteTitle']);

$smarty->interPlay('register.tpl');

?>